<template>
    <!--  <div class="page-container">-->
    <!-- 背景组件 -->
    <code-rain class="code-rain-background"></code-rain>
      <div class="parent1">
        <!-- 个人信息内容 -->
        <div class="content" v-for="u in user" :key="u.id">
          <div class="img">
            <img :src="u.avatar?u.avatar:avatarUrl" alt="img">
            <div class="overlay">
              <label for="avatar-upload">
                <img src="@/assets/相机.png" alt="相机" class="icon">
              </label>
            </div>
          </div>
          <div class="name">
            <p>{{ u.username?u.username:name }}</p>
          </div>
          <div class="list-person">
            <ul>
              <li @click="openFansModal">粉丝：{{ fans }}</li>
              <li @click="openFollowedModal">关注：{{ followed }}</li>
              <li> 性别:{{genderText}}</li>

            </ul>
          </div>
          <div class="bio"><p>简介：{{u.bio?u.bio:bio}}</p> </div>
          <div class="birthday"><p>生日：{{formatDate(u.birthday)}}</p></div>
        </div>
        <!-- 添加关注按钮 -->
        <div class="follow-button" v-if="!isOwner">
          <el-button
            :type="isFollowing ? 'danger' : 'primary'"
            @click="handleFollow"
          >
            {{ isFollowing ? "取消关注" : "关注" }}
          </el-button>
        </div>
      </div>
      <div class="parent2">
        <div class="left-content">
          <div class="content2">
            <h3>时间线</h3>
            <el-timeline>
              <el-timeline-item
                v-for="post in posts"
                :key="post.id"
                :timestamp="formatDate(post.createdAt)"
              >
                <el-card>
                  <h4>{{ post.title }}</h4>
                  <p>{{ post.userName }} 发布于 {{ formatDate(post.createdAt) }}</p>
                  <p>{{ post.content }}</p>
                </el-card>
              </el-timeline-item>
            </el-timeline>
          </div>
          <div class="content3">
            <h3>归档</h3>
            <ul>
              <li v-for="(months, year) in archives" :key="year">
                <strong>{{ year }} 年</strong>
                <ul>
                  <li
                    v-for="(count, month) in months"
                    :key="month"
                    style="cursor: pointer;"
                  >
                    <span>{{ month }} 月</span>：<span>{{ count }} 篇</span>
                  </li>
                </ul>
              </li>
            </ul>
          </div>
        </div>
        <div
          class="content4"
          v-infinite-scroll="loadMorePosts"
          infinite-scroll-disabled="loading || noMore"
          infinite-scroll-distance="10"
        >
          <div class="card-container">
            <div
              class="post-card"
              v-for="post in posts"
              :key="post.id"
              @click="handlePostClick(post)"
            >
              <div class="card-avatar">
                <img :src="post.userAvatar || '/images/default-avatar.png'" alt="头像" />
              </div>
              <div class="card-content">
                <h3 class="card-title">{{ post.title }}</h3>
                <p class="card-time">{{ formatDate(post.createdAt) }}</p>
                <!-- 点赞数和评论数 -->
                <div class="card-stats">
                  <span><i class="fas fa-heart"></i> {{ post.likeCount }} 点赞</span>
                  <span><i class="fas fa-comment"></i> {{ post.commentCount || 0 }} 评论</span>
                </div>
              </div>
            </div>
          </div>
          <!-- 加载提示 -->
          <div v-if="loading" class="loading">加载中...</div>
          <div v-if="noMore" class="no-more">没有更多数据了</div>
        </div>
      </div>
  <!-- 粉丝列表弹窗 -->
  <div v-if="showFansModal" class="modal-overlay" @click.self="closeFansModal">
    <div class="modal">
      <h2>粉丝列表</h2>
      <ul class="user-list">
        <li v-for="follower in followers" :key="follower.id" class="user-item" @click="handleToOtherPage(follower.id)">
          <div class="user-wrapper">
            <img :src="follower.avatar || '/public/images/default-avatar.png'" alt="头像" class="avatar" />
            <span class="username">{{ follower.username }}</span>
          </div>
        </li>
      </ul>
    </div>
  </div>
  <!-- 关注列表弹窗 -->
  <div v-if="showFollowedModal" class="modal-overlay" @click.self="closeFollowedModal">
    <div class="modal">
      <h2>关注列表</h2>
      <ul class="user-list">
        <li v-for="followedUser in followedUsers" :key="followedUser.id" class="user-item" @click="handleToOtherPage(followedUser.id)">
          <div class="user-wrapper">
            <img :src="followedUser.avatar || '/public/images/default-avatar.png'" alt="头像" class="avatar" />
            <span class="username">{{ followedUser.username }}</span>
          </div>
        </li>
      </ul>
    </div>
  </div>
</template>
<script setup>
import CodeRain from '@/components/codeRain.vue'
import {useRoute} from 'vue-router'
import {API_BASE_URL} from "@/config/config"
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { computed, onMounted, ref, watch } from 'vue'
import {useRouter} from 'vue-router'
const router = useRouter()
const route = useRoute()
// 用户信息
const name = ref('LQJ')
//头像URL
const avatarUrl = ref('https://blog-lqj-1331162601.cos.ap-guangzhou.myqcloud.com/avatar_image/742d3cc2-89b9-43e6-af58-1abbd75e0290.jpg')
// 粉丝列表和关注列表
const followers = ref([]);
const followedUsers = ref([]);
//简介
const bio = ref('这个人很懒，什么也没留下...');
//性别
const gender = ref('other')
//粉丝数量
const fans = ref(0)
//关注的人的数量
const followed = ref(0);
// const bir = ref(0)
//性别映射
const genderMap = {
  male: "男",
  female: "女",
  other: "未定义"
};
const userId = ref()
//分页查询
const total = ref(0);
const page = ref(1)
const pageSize = ref(100)
const posts = ref([]);
const loading = ref(false); // 是否正在加载
const noMore = ref(false); // 是否没有更多数据
const user = ref([])
//格式化时间
const formatDate = (dateString)=>{
  const date = new Date(dateString);
  return date.toLocaleDateString();
}
// 弹窗控制
const showFansModal = ref(false); // 控制粉丝列表弹窗的显示
const showFollowedModal = ref(false); // 控制关注列表弹窗的显示
// 打开粉丝列表弹窗
const openFansModal = () => {
  showFansModal.value = true;
};

// 关闭粉丝列表弹窗
const closeFansModal = () => {
  showFansModal.value = false;
};

// 打开关注列表弹窗
const openFollowedModal = () => {
  showFollowedModal.value = true;
};

// 关闭关注列表弹窗
const closeFollowedModal = () => {
  showFollowedModal.value = false;
};
// 性别的中文显示
const genderText = computed(() => genderMap[gender.value] || "未知");
const getUserData =async()=> {
  const GET_USER_URL = `${API_BASE_URL}/userInfo`
  const userId = route.params.userId
  try {
    const response = await axios.get(GET_USER_URL, {
      params:{
        userId: userId
      }
    })
    if (response.data.code === 200) {
      // name.value = response.data.user.username;
      // if (response.data.user.avatar !== null) {
      //   avatarUrl.value = response.data.user.avatar;
      // }
      // if (response.data.user.bio !== null) {
      //   bio.value = response.data.user.bio;
      // }
      fans.value = response.data.followerCount;
      followed.value = response.data.followedCount;
      followers.value = response.data.followers;
      followedUsers.value = response.data.followedUsers;
      // if (response.data.user.birthday !== null) {
      //   bir.value = response.data.user.birthday
      // }
      // if (response.data.user.gender !== null) {
      //   gender.value = response.data.user.gender
      // }
      user.value = response.data.users
    }
  } catch (error) {
    ElMessage.error("error" + error.message)
  }
}
// 是否是当前用户
const isOwner = ref(false); // 如果是当前用户，隐藏关注按钮

// 关注状态
const isFollowing = ref(false);

// 检查是否已关注
const checkFollowStatus = async () => {
  try {
    const userId = route.params.userId; // 被关注用户的 ID
    const response = await axios.get(
      `${API_BASE_URL}/follow/status/${userId}`,
      { withCredentials: true }
    );
    if (response.data.code === 200) {
      isFollowing.value = response.data.isFollowing;
    }
  } catch (error) {
    ElMessage.error("获取关注状态失败：" + error.message);
  }
};

// 关注用户
const followUser = async () => {
  try {
    const userId = route.params.userId; // 被关注用户的 ID
    const response = await axios.post(
      `${API_BASE_URL}/follow/${userId}`,
      {},
      { withCredentials: true }
    );
    if (response.data.code === 200) {
      isFollowing.value = true;
      getUserData()
      ElMessage.success("关注成功");
    }
  } catch (error) {
    ElMessage.error("关注失败：" + error.message);
  }
};

// 取消关注用户
const unfollowUser = async () => {
  try {
    const userId = route.params.userId; // 被关注用户的 ID
    const response = await axios.delete(
      `${API_BASE_URL}/follow/${userId}`,
      { withCredentials: true }
    );
    if (response.data.code === 200) {
      isFollowing.value = false;
      getUserData()
      ElMessage.success("取消关注成功");
    }
  } catch (error) {
    ElMessage.error("取消关注失败：" + error.message);
  }
};

// 处理关注按钮点击
const handleFollow = () => {
  if (isFollowing.value) {
    unfollowUser();
  } else {
    followUser();
  }
};
//更新归档
const archives = ref({}); // 响应式变量存储归档数据

const updateArchives = (postList) => {
  const archiveData = {};

  postList.forEach((post) => {
    const date = new Date(post.createdAt);
    const year = date.getFullYear();
    const month = date.getMonth() + 1; // 月份从 0 开始，需要加 1

    // 初始化年份和月份的分组
    if (!archiveData[year]) {
      archiveData[year] = {};
    }
    if (!archiveData[year][month]) {
      archiveData[year][month] = 0;
    }

    // 统计该月份的帖子数量
    archiveData[year][month]++;
  });

  archives.value = archiveData; // 更新响应式归档数据
};
//获取当前用户帖子数据
const getPostsByUser = async (isLoadMore = false) => {
  try {
    loading.value = true;
    const response = await axios.get(`${API_BASE_URL}/posts/searchByUser`, {
      params: {
        userId: route.params.userId, // 当前用户的 ID
        page: page.value, // 当前页码
        pageSize: pageSize.value, // 每页加载的数量
      },
    });

    if (response.data.code === 200) {
      const { posts: newPosts, total: totalPosts } = response.data.data;

      total.value = totalPosts; // 更新总帖子数

      if (isLoadMore) {
        // 加载更多时追加数据
        posts.value = [...posts.value, ...newPosts];
      } else {
        // 初次加载，替换数据
        posts.value = newPosts;
      }

      // 更新归档数据
      updateArchives(posts.value);

      // 检查是否已加载完所有帖子
      noMore.value = posts.value.length >= total.value || newPosts.length === 0;

      // 如果还有更多数据可加载，增加页数
      if (!noMore.value) {
        page.value += 1;
      }
    } else {
      ElMessage.error("获取帖子失败：" + response.data.message);
    }
  } catch (error) {
    console.error("加载帖子失败：", error.message);
  } finally {
    loading.value = false; // 无论是否成功，结束加载状态
  }
};
const handlePostClick = (post) => {
  router.push({ name: "Post_detail", params: { id: post.id, userId: post.userId } });
};
const loadMorePosts = () => {
  if (loading.value || noMore.value) return; // 正在加载或没有更多数据时不继续加载
  getPostsByUser(true); // 加载更多数据
};
//点击粉丝列表的用户就显示那个人的主页
const handleToOtherPage = (id) => {
  router.push({ name: 'Other_user', params: { userId: id } })
}

//异步加载数据
onMounted(async () => {
  const userIdFromRoute = route.params.userId;
  if (userIdFromRoute) {
    userId.value = userIdFromRoute; // 初始化 userId
    await getUserData(); // 加载用户信息
    await getPostsByUser(); // 加载用户帖子
    await checkFollowStatus(); // 检查关注状态
  } else {
    ElMessage.error("未能获取用户 ID，无法加载数据！");
  }
});

watch(
  () => route.params.userId, // 监听路由参数的变化
  async (newUserId) => {
    if (newUserId) {
      userId.value = newUserId; // 更新 userId
      await getUserData(); // 重新加载用户信息
      await getPostsByUser(); // 重新加载用户帖子
      await checkFollowStatus(); // 检查关注状态
    }
  }
);


</script>
<style scoped>
/*.all{
  height: 100vh;
  width:100%;
  padding: 0;
  margin: 0;
}*/
.parent1{
  height: 400px;
  width: 100%;
  display: flex;
  max-width: 100vw;
  left:0;
}
.parent2{
  width: 100%;
  height: 70vh;
  display: flex;
  position: relative;
  left: 0;
  gap: 10px;
}
/* 背景组件样式 */
.code-rain-background {
  position: fixed; /* 固定定位 */
  top: 0;
  left: 0;
  width: 100%; /* 覆盖整个页面宽度 */
  height: 100%; /* 覆盖整个页面高度 */
  z-index: -1; /* 确保在其他内容下方 */
}
.content {
  display: flex;
  position: absolute; /* 固定定位 */
  width: 77vw;
  height: 200px;
  background-color: white;
  z-index: 2;
  top: 30%; /* 元素顶部居中 */
  left: 35.53%; /* 元素水平居中 */
  transform: translate(-30%, -50%); /* 调整元素中心点 */
  max-width: 100%;
  border-radius: 20px;
}

/* 图片容器样式 */
.img {
  width: 90px; /* 固定宽度 */
  height: 90px; /* 固定高度 */
  overflow: hidden; /* 隐藏超出部分 */
  border-radius: 50%;
  position: relative;
  cursor: pointer;
  top: -10px;
  justify-content: center;
  align-items: center;
  margin: 3px;
}
.list-person {
  position: relative;
  left: 40px;
  margin-top: 80px;
  display: flex;
  gap: 10px;
  cursor: pointer;
}

.list-person ul li {
  display: inline-block;
}

.list-person li:not(:last-child)::after {
  content: "|"; /*分隔符的内容*/
  margin-left: 10px; /*分隔符前的间距*/
  margin-right: 10px; /*分隔符后的间距*/
}
.content2, .content3 {
  display: flex;
  width: 30vw;
  height: 220px;
  background-color: white;
  z-index: 2;
  max-width: 100%;
  left: 20.1%;
  margin-top: 10px;
  overflow: auto;
  border-radius: 20px;
}

.content4 {
  display: flex;
  flex-direction: column;
  background-color: white;
  padding: 20px;
  position: relative;
  height: 400px; /* 固定高度 */
  overflow-y: auto; /* 可滚动 */
}

/* 卡片容器样式 */
.card-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 一行三个卡片 */
  gap: 20px; /* 卡片间距 */
}

.left-content {
  position: relative;
  display: flex;
  flex-direction: column;
  left: 12%;
}

.menu_personal ul{
  list-style: none;
  display: flex;
  padding: 0;
  width: 100%;
  margin: 0;
}
.menu_personal li {
  flex: 1;
  text-align: center;
}
.menu_personal li:hover{
  color: #007bff;
}
.menu_personal ul::after{
  content: "";
  position: absolute;
  bottom: 5px;
  left: 0;
  width: 20%;
  height: 3px;
  background-color: #007bff;
  transition: transform 0.3s ease;
  z-index: 2;
  transform:translateX(v-bind(sliderOffset));
}
.bio{
  position: absolute;
  left: 12.2%;
  top:55%
}
.birthday{
  position: absolute;
  left: 12.2%;
  top:69%
}
/* 用户列表样式 */
.user-list {
  list-style: none;
  padding: 0;
  margin: 0;
}

.user-item {
  width: 100%; /* 占满弹窗宽度 */
  border-bottom: 1px solid #eee;
  box-sizing: border-box;
}

.user-item:last-child {
  border-bottom: none;
}

/* 包裹头像和用户名的容器 */
.user-wrapper {
  display: flex;
  align-items: center;
  height: 90px; /* 固定高度 */
  padding: 10px;
  box-sizing: border-box;
  box-shadow: 0 4px 8px rgba(0,0,0,0.2);
  border-radius: 10px;
}

/* 头像样式 */
.avatar {
  width: 50px; /* 固定宽度 */
  height: 50px; /* 固定高度 */
  border-radius: 50%; /* 圆形头像 */
  margin-right: 10px;
  object-fit: cover; /* 确保图片填充 */
}

/* 用户名样式 */
.username {
  font-size: 16px;
  color: #333;
}

/* 图片样式 */
.img img {
  width: 100%; /* 确保图片宽度覆盖容器 */
  height: 100%; /* 确保图片高度覆盖容器 */
  object-fit: cover; /* 使图片以覆盖方式填充容器，裁剪多余部分 */
  object-position: center; /* 保证显示图片的中心部分 */
}
/*名字样式*/
.name p {
  position: fixed;
  left: 160px;
  margin-top: 20px;
  text-align: center;
  font-size: 2rem;
  font-weight: bold;
  color: #333;
}
/*弹窗背景遮罩 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5); /* 半透明遮罩 */
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 999;
}

/* 弹窗样式 */
.modal {
  background: #fff;
  padding: 20px;
  border-radius: 10px;
  width: 400px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  text-align: center;
  position: relative;
}

.follow-button {
  position: absolute;
  top: 22%;
  right: 15%;
  z-index: 3;
}

.follow-button .el-button {
  font-size: 16px;
  padding: 5px 15px;
  border-radius: 5px;
}
.content4{
  display: flex;
  background-color: white;
  height: 410px;
  width: 849.5px;
  position: absolute;
  z-index: 2;
  left: 43%;
  margin-top: 10px;
  border-radius:20px
}

/* 卡片容器样式 */
.card-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 一行三个卡片 */
  gap: 20px; /* 卡片间距 */
}

/* 卡片容器 */
.card-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr); /* 一行三个卡片 */
  gap: 20px; /* 卡片之间的间距 */
}

/* 单个卡片 */
.post-card {
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease, box-shadow 0.3s ease;
  cursor: pointer;
}

.post-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2);
}

/* 卡片的头像部分 */
.card-avatar {
  width: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 15px; /* 头像上方的间距 */
}

.card-avatar img {
  width: 50px; /* 设置头像宽度为 50px */
  height: 50px; /* 设置头像高度为 50px */
  border-radius: 50%; /* 圆角设置为 50%（圆形） */
  object-fit: cover; /* 确保图片内容完整显示且不变形 */
  border: 1px solid #ddd; /* 可选：给头像加边框 */
}

/* 卡片的内容部分 */
.card-content {
  padding: 15px;
  text-align: center;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
  margin: 0;
  margin-bottom: 10px;
}

.card-time {
  font-size: 14px;
  color: #999;
  margin: 0;
}

/* 点赞和评论数区域 */
.card-stats {
  display: flex;
  justify-content: space-between; /* 两端对齐 */
  align-items: center;
  margin-top: 10px;
  font-size: 14px;
  color: #666;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 5px; /* 图标与文字之间的间距 */
}
/* 点赞和评论数区域 */
.card-stats {
  display: flex;
  justify-content: space-between; /* 两端对齐 */
  align-items: center;
  margin-top: 10px;
  font-size: 14px;
  color: #666; /* 默认文字颜色 */
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 5px; /* 图标和文字之间的间距 */
  font-size: 14px;
}

.stat-item i {
  color: #999; /* 图标颜色 */
  font-size: 16px;
}
/* 加载提示样式 */
.loading,
.no-more {
  text-align: center;
  padding: 10px;
  color: #666;
  width: 100%;
}
/*.content3 {
  padding: 20px;
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  overflow-y: auto;
}*/

.content3 h3 {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
}

.content3 ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.content3 li {
  margin-bottom: 8px;
  cursor: pointer;
}

.content3 li:hover {
  color: #007bff;
  text-decoration: underline;
}
</style>
